<?php

// +----------------------------------------------------------------------
// | TAODUDU.COM  [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.taodudu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: ubten <462193409@qq.com> http://www.ubten.com/
// +----------------------------------------------------------------------

namespace Home\Controller;
use Home\Controller\BaseController;

class BuyingController extends BaseController {
    
    function _initialize() {
        parent::_initialize();
        if(empty(session('user_id'))){
            $forward = getUrl();
            redirect('/Login/login?forward='.$forward);
            exit;
        }
    }

    public function index() {
        
        $seckill_id = I('id');
        //如果获取不到参数直接跳转等到首页
//        if (empty($seckill_id) && $seckill_id < 1) {
//            redirect(HOME_URL);
//            die;
//        }
        //获取用户的默认邮寄地址
        $where['user_id'] = session('user_id');
        $where['is_default'] = "1";
        $address = M('address')->where($where)->find();
        
        $map['seckill_id'] = $seckill_id;
        $seckill = M('seckill')->where($map)->find();
        $this->assign("seckill", $seckill);
         
        $maps['goods_id'] = $seckill['seckill_goods_id'];
        $goods =M('goods')->where($maps)->find();
        $this->assign("goods", $goods);

        $this->assign("address", $address);
        $this->display();
    }
    
     public function check(){
        $seckill_id = I('seckill_id');
        $seckill = M('seckill')->where('seckill_id='.$seckill_id)->find();
        if($seckill){
            //查询销售量
            $Order = M("order_goods");
            $whe['oi.goods_type'] = 4;
            $whe['os.order_state'] = array('EGT',20);
            $whe['oi.goods_id'] = I('goods_id');
            $count = $Order->alias('oi')->join('LEFT JOIN __ORDER__ os ON oi.order_id = os.order_id')->where($whe)->count();
            if($count >=$seckill['seckill_nums']){
                //更新状态
                M('seckill')->where('seckill_id='.$seckill_id)->setField('seckill_state',0);
                $a['state'] = FALSE;
                $a['msg'] = "已售罄";
                $this->ajaxReturn($a);
                exit;
            }
            //获取用户是否已经购买过此商品
            $where['oi.goods_type'] = 4;
            $where['oi.user_id'] = session('user_id');
            $where['oi.goods_id'] = I('goods_id');
            $where['os.order_state'] = array('EGT',20);
            $counts = $Order->alias('oi')->join('LEFT JOIN __ORDER__ os ON oi.order_id = os.order_id')->where($where)->find();
            if ($counts) {
                $a['state'] = FALSE;
                $a['msg'] = "每个用户只能购买一次！";
                $this->ajaxReturn($a);
                exit;
            }else{
                $a['state'] = true;
                $this->ajaxReturn($a);
            }
        }else{
                $a['state'] = FALSE;
                $a['msg'] = "错误的信息！";
                $this->ajaxReturn($a);
                exit;
        }
    }
    
    //提交立即购买
    public function DoNowBuy() {
        if (IS_POST) {
            //生成订单和订单产品
            //根据用户购买不同商家的商品创建相应的订单
            //合并支付时，生成支付的ID，并与订单的ID进行关联
            //order_id 和 pay_sn  订单ID和支付ID
            //订单ID是唯一的，一个订单对应一个订单ID，一个订单可对应一个支付ID（单商品购买或者同商家的购买）属于单品付款，一个支付ID对应多个订单ID（多商家的商品购买）属于合并付款
            //每次的单品支付或者合并支付支付的是动态重新获取的，支付的同时修改相应的支付ID
            //生成订单商品的同时，减少相应的库存
            //生成唯一的支付单号
            $paySN = create_trade_id();
            $order_sn = create_trade_id();
            $goods_id = I('goods_id');       //商品ID
            $goods_num = I('goods_num');     //商品数量
            //
            //根据各属性的ID计算出以下数据：
            $where['goods_id'] = $goods_id;
            $goods = M('goods')->where($where)->find();
            
            $goods['goods_guige'] = "默认";
            //减少商品的库存
            $map['seckill_goods_id'] = $goods_id;
            $price = M('seckill')->where($map)->getField('seckill_price');
            $order_price = price($price*$goods_num);
            $goods['total_price'] = $order_price;
            M('seckill')->where($map)->setDec('seckill_nums', $goods_num);
            
            //生成订单数据列表
            $order_message = I('order_message');
            $payment = I('payment');     //支付方式
            //根据商户的ID进行循环生成订单并将相应的商品增加到订单从表里
            $data['order_sn'] = $order_sn;
            $data['pay_sn'] = $paySN;
            $data['store_id'] = $goods['store_id'];
            $data['store_name'] = $goods['store_name'];
            $data['user_id'] = session('user_id');
            $data['user_name'] = session('user_name');
            $data['add_time'] = NOW_TIME;
            $data['payment_code'] = $payment;
            $data['discount_fee'] = 0;
            $data['shipping_fee'] = 0;
            $data['goods_amount'] = $order_price;
            $data['order_from'] = 1;
            $re = M('order')->add($data);
            //订单生成之后，将相应的商品加入到表里
            if ($re) {
                $where['is_default'] = "1";
                $where['user_id'] = session('user_id');
                $address = M('address')->where($where)->find();
                //订单属性表
                $arr['order_id'] = $re;
                $arr['store_id'] = $goods['store_id'];
                $arr['order_message'] = $order_message;
                $arr['address_id'] = $address['address_id'];
                $arr['reciver_name'] = $address['true_name'];
                $arr['reciver_info'] = serialize($address);
                $arr['reciver_areaid_id'] = $address['area_id'];
                $arr['reciver_city_id'] = $address['city_id'];
                $arr['promotion_info'] = '商品秒杀';
                M('orderCommon')->add($arr);
                $this->addBuyGoods($goods, $re, $goods_num);
            } else {
                $this->error('系统异常请稍候再试！');
            }
            switch ($payment) {
                case "weixin":
                    //增加之后跳转到微信支付页面
                    // /Wxpay/JsApipay?id=
                    //$url = U('/Wxpay/JsApipay', array('id' => $data['order_sn']));
                    $url = "/Wxpay/paymentConfirm?key=" . auth_encode($data['pay_sn']);
                    redirect($url);
                    break;
                case "alipay":
                    //增加之后跳转到支付宝支付页面
                    $url = HOME_URL . U('/Pay/index/', array('id' => $data['pay_sn'], 'paytype' => 'ALIPAY'));
                    redirect($url);
                    break;
                case "upcash":
                    //增加之后跳转到银联支付页面
                    $url = HOME_URL . U('/UnionPay/doPay', array('id' => $data['pay_sn']));
                    redirect($url);
                    break;
                default:
                    break;
            }
        } else {
            $this->redirect('/User/index');
        }
    }
    
    //增加相应的商品(立即购买下订单)
    protected function addBuyGoods($arr, $order_id, $goods_num) {
        //判断是否是统一规格，如果是：取商品自身的图片和价格，否：根据属性表取值
        $datas['order_id'] = $order_id;
        $datas['goods_id'] = $arr['goods_id'];
        $datas['goods_title'] = $arr['goods_title'];
        $datas['goods_price'] = $arr['goods_price'];
        $datas['goods_num'] = $goods_num;
        $datas['goods_image'] = $arr['goods_thumb'];
        $datas['goods_attri_info'] = $arr['goods_guige'];
        $datas['goods_pay_price'] = $arr['total_price'];
        $datas['store_id'] = $arr['store_id'];
        $datas['user_id'] = session('user_id');
        $datas['goods_class'] = $arr['goods_class'];
        M('orderGoods')->add($datas);
    }
    
    public function getGoodsAttr(){
        $jj = I('jj');
        $id = I('id');
        $goods_id = I('goods_id');
        $re =M('seckill')->where('seckill_id='.$id)->find();
        if($re['seckill_sale'] >= $re['seckill_nums']){
            $a['xq'] = 2;
            $this->ajaxReturn($a);
        }else if($jj > $re['seckill_limit']){
            $a['xq'] = 1;
            $a['limit'] = $re['seckill_limit'];
            $this->ajaxReturn($a);
        }else{
            $a['xq'] = 3;
            $a['zj'] = price($jj*$re['seckill_price']);
            $this->ajaxReturn($a);
        }
    }

}
